package com.x2.modular.system.utils;

import com.x2.base.pojo.node.LayuiTreeNode;
import com.x2.core.util.ListUtil;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class TreeFilter {

    /**
     * 按照部门进行过滤，过滤后保留所有父和子，删除兄弟节点
     *
     * @param tree 树结构
     * @param deptScope 111,2222
     * @return
     */
    public static  List<LayuiTreeNode> filter(List<LayuiTreeNode> tree, String deptScope) {
        if (deptScope == null || deptScope.trim().length() == 0) {
            return tree;
        }
        Long[] depts = ListUtil.toLongArr(deptScope);
        List<Long> selectedDept = new ArrayList<>();
        selectedDept.addAll(Arrays.asList(depts));
        retain(tree.get(0),selectedDept);
        return tree;
    }

    /**
     *
     * @param node
     * @param deptList
     * @return
     */
    private static boolean retain(LayuiTreeNode node, List<Long> deptList) {
        if(deptList.contains(node.getId())){
            return true;
        }
        List<LayuiTreeNode> newChildList= new ArrayList<>();
        for(LayuiTreeNode child:node.getChildren()){
            if(retain(child,deptList)){
                newChildList.add(child);
            }
        }
        if(newChildList.size()==0){
            return false;
        }
        node.setChildren(newChildList);
        return true;
    }
}
